package com.example.wujinapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.wujinapi.comm.R;
import com.example.wujinapi.entity.Favourites;
import com.example.wujinapi.entity.Products;
import com.example.wujinapi.service.FavouritesService;
import com.example.wujinapi.service.ProductsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * (Favourites)表控制层
 *
 * @author makejava
 * @since 2023-07-10 22:36:08
 */
@RestController
@RequestMapping("favourites/")
public class FavouritesController{
    /**
     * 服务对象
     */
    @Resource
    private FavouritesService favouritesService;

    @Resource
    private ProductsService productsService;

    /**
     * 获取我的收藏数据
     */
    @GetMapping("/getFavourites/{userid}")
    public R getFavourites(@PathVariable("userid") Integer userid){
        try {
            List<Map<String,Object>> getFavourites=favouritesService.getFavourites(userid,1,10);
            List<JSONObject> outPutList=new ArrayList<>();
            //获取对应的商品数据
            getFavourites.forEach(item->{
                JSONObject TempData= JSON.parseObject(JSON.toJSONString(item));
                TempData.put("productInfo",productsService.getProductById(Integer.valueOf(item.get("pid").toString())));
                outPutList.add(TempData);
            });
            return R.ok().put("data",outPutList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(400,"失败");
        }
    }


    /**
     * 添加收藏
     */
    @GetMapping("/addFavourites/{userid}/{productId}")
    public R addFavourites(@PathVariable("userid") Integer userid,@PathVariable("productId") Integer productId){
        try {
            if(userid>0 && productId>0){
                Favourites favourites=new Favourites();
                favourites.setUserid(userid);
                favourites.setPid(productId);
                favouritesService.addFavourite(favourites);
                return R.ok("添加收藏成功").put("favId",favourites.getId());
            }else{
                return R.error(400,"添加收藏失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(400,"添加收藏失败");
        }
    }



    /**
     * 删除收藏
     */
    @GetMapping("/deleteFavourites/{favId}")
    public R deleteFavourites(@PathVariable("favId") Integer favId){
        try {
            favouritesService.deleteFavourite(favId);
            return R.ok("已移除收藏");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(400,"删除收藏失败");
        }
    }



}

